package cn.globalph.housekeeper.ui.main

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import cn.globalph.housekeeper.BuildConfig
import cn.globalph.housekeeper.Event
import cn.globalph.housekeeper.data.model.UpdateModel
import cn.globalph.housekeeper.data.params.LocationParam
import cn.globalph.housekeeper.ui.BaseViewModel
import kotlinx.coroutines.launch
import java.lang.Exception

const val UPLOAD_DELAY:Long = 5*60*1000
const val DELAY_DELTA:Long = 2*1000
class MainViewModel (
    private val mainRepository: MainRepository
):BaseViewModel(){
    private var lastTime:Long = -1

    var updateModel = MutableLiveData<UpdateModel>()

    var showUpdateDialog = MutableLiveData<Boolean>()


    fun start(versionCode:Int,ignoreVersionCode:Int){
        viewModelScope.launch {
            val model = mainRepository.checkUpdate(versionCode)
            if(model.isSuccessful()){
                var update = model.data
                updateModel.value = update
                if(update == null || update.appurl.isNullOrEmpty()
                    ||ignoreVersionCode>=update.versioncode){
                    return@launch
                }
                showUpdateDialog.value = true
            }
        }

    }

    fun uploadLocation(lat:String,lon:String){
        if(lastTime == -1L || System.currentTimeMillis()-lastTime> UPLOAD_DELAY-DELAY_DELTA){
            lastTime = System.currentTimeMillis()
            viewModelScope.launch {
                try{
                    val model = mainRepository.uploadLocation(LocationParam("$lat,$lon"))
                    if(model.isCertFail()) _tokenEvent.value = Event(true)
                }catch (e:Exception){
                    if(BuildConfig.DEBUG) e.printStackTrace()
                }
            }
        }
    }
}